package com.ruoyi.wisdom.utils;

import org.springframework.lang.Nullable;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Objects;

public class FileUtils {

    // 获取文件内容
    public static String getContent(@Nullable InputStream inputStream, Charset charset) throws IOException {
        if (Objects.isNull(inputStream)) return "";
        InputStreamReader reader = new InputStreamReader(inputStream, charset);
        int length;
        StringBuilder sb = new StringBuilder();
        while ((length = reader.read()) != -1) {
            sb.append((char) length);
        }
        reader.close();
        return sb.toString();
    }

    /**
     * 下载网络图片上传到服务器上
     *
     * @param httpUrl    图片网络地址
     * @param filePath   图片保存路径
     * @param myFileName   图片文件名(null时用网络图片原名)
     * @return
     */
    public static String getHtmlPicture(String httpUrl, String filePath, String myFileName) {

        URL url; //定义URL对象url

        BufferedInputStream in; //定义输入字节缓冲流对象in

        FileOutputStream file; //定义文件输出流对象file

        try {

            String fileName = null == myFileName ? httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", "") : myFileName; //图片文件名(null时用网络图片原名)

            url = new URL(httpUrl); //初始化url对象

            in = new BufferedInputStream(url.openStream()); //初始化in对象，也就是获得url字节流

            //file = new FileOutputStream(new File(filePath +"\\"+ fileName));

            file = new FileOutputStream(mkdir(filePath, fileName));

            int t;

            while ((t = in.read()) != -1) {

                file.write(t);

            }

            file.close();

            in.close();

            return fileName;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 判断路径是否存在，否：创建此路径
     *
     * @param dir        文件路径
     * @param realName   文件名
     * @return
     * @throws IOException
     */
    public static File mkdir(String dir, String realName) throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        return file;
    }

    /**
     * 获取文件名字
     * @param url
     * @return
     */
    public static String getFileName(String url){
        String fName = url.trim();

        String fileName = fName.substring(fName.lastIndexOf("/")+1);
        //或者
        //String fileName = fName.substring(fName.lastIndexOf("\\")+1);
        return fileName;
    }

    /**
     * 删除文件
     * @param filePath
     */
    public static boolean deleteFile(String filePath){
        // 获取图片信息
        File tmpFile = new File(filePath);
        if (tmpFile.exists()) {
            return tmpFile.delete();
        }
        return false;
    }
}
